#include "launchbar.h"
#include <QDesktopWidget>

LaunchBar::LaunchBar(QWidget *parent)
    : QWidget(parent)
{
    edit = new QLineEdit(this);
    layout = new QVBoxLayout(this);
    completer = new QCompleter(edit);
    this->setupUi();

    edit->setCompleter(completer);
    connect(edit, &QLineEdit::returnPressed,
            this, &LaunchBar::enterPressed);
}

LaunchBar::~LaunchBar(){}

void LaunchBar::setupUi()
{
    this->resize(600, 50);
    int center = (QApplication::desktop()->width() -
                  this->width()) / 2;
    this->move(center, 50);
    this->setWindowFlags(Qt::WindowStaysOnTopHint |
                             Qt::FramelessWindowHint);

    layout->addWidget(edit);
    this->setLayout(layout);

    this->setStyleSheet("font-size:12pt; "
                        "font-family:'Consolas',"
                        "'Microsoft YaHei'; "
                        "background-color: white");
    this->setWindowIcon(QIcon(":/icon/launch"));
}

void LaunchBar::enterPressed()
{
    emit execute(edit->text());
    edit->clear();
    this->showHide();
}

void LaunchBar::showHide()
{
    if(this->isHidden())
    {
        this->show();
        this->activateWindow();
        QApplication::setActiveWindow(this);
        this->raise();
    }
    else
    {
        this->hide();
    }
}

void LaunchBar::setEditCompleterModel(QStringListModel &model)
{
    completer->setModel(&model);
}

Qt::CaseSensitivity LaunchBar::completerSensitiveToggle()
{
    if(completer->caseSensitivity() == Qt::CaseSensitive)
    {
            completer->setCaseSensitivity(Qt::CaseInsensitive);
            return Qt::CaseInsensitive;
    }
    completer->setCaseSensitivity(Qt::CaseSensitive);
    return Qt::CaseSensitive;
}
